//
//  RHHousesDetailedSearchVC.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/30.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import SVProgressHUD

class RHHousesDetailedSearchVC: RHViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate{
    
    var tableView: UITableView?
    let pickerView = RHPickerView()
    var pickerViewDataArray = [""]
    var array:[String] = [NSLocalizedString("QueryMethodsText", comment: ""),
                          NSLocalizedString("QueryConditionsText", comment: ""),
                          NSLocalizedString("HousingTypesText", comment: ""),
                          NSLocalizedString("bedroomNumberText", comment: ""),
                          NSLocalizedString("bathNumberText", comment: ""),
                          NSLocalizedString("buildingAgeText", comment: ""),
                          NSLocalizedString("HousingSizeText", comment: "") + "(平)",
                          NSLocalizedString("HousingPriceText", comment: "")  + "(万)"
                          ]
    
    let queryMethodsArray:[String] = [NSLocalizedString("ZipCodeText", comment: ""),
                                      NSLocalizedString("Address", comment: ""),
                                      NSLocalizedString("City", comment: "")]
    var HousingTypesArray:[String] = []
    let bedroomNumberArray:[String] = ["1","2","3","4","5","6"]
    let bathNumberArray:[String] = ["1","2","3","4","5","6"]
    var buildingAgeArray:[String] = []
    let minSizeArray:[String] = ["0-100","100-200","200-400","400-800"]
    let maxPriceText:[String] = ["0-100","100-200","200-400","400-800","800-1600"]
    var pickerViewDataStorage = Array<Any>()
    var pickerViewIndex = 0
    var HouseTypeModel = RHHouseTypeModel()
    var submit = UIButton()
    var datePicker = RHDatePicker()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("DetailedSearchText", comment: "")
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_shutDown"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancel))
        loadTableView()
        loadPickerView()
        loadDoHouseTypeApi()
        datePicker.RH_CreateDatePicker(viewController: self)
        self.datePicker.confirmButton.addTarget(self, action: #selector(datePickerConfirmClick), for: .touchUpInside)
    }
    
    @objc func datePickerConfirmClick() {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        pickerViewDataStorage[5] = formatter.string(from: self.datePicker.datePicker.date)
        self.datePicker.hideView()
        self.tableView?.reloadData()
    }
    
    func loadDoHouseTypeApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doHouseType(result: {[weak self] (msg, model) in
            guard let weakSelf = self else { return }
            weakSelf.HouseTypeModel = model as! RHHouseTypeModel
            SVProgressHUD.dismiss()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadPickerView(){
        pickerViewDataStorage = Array<String>(repeating: "", count: array.count)
        pickerView.RH_CreatePickerView(viewController: self)
        pickerView.confirmButton.addTarget(self, action: #selector(ConfirmClick), for: .touchUpInside)
    }
    
    func loadTableView(){
        self.tableView = RHTableView(frame: CGRect.zero, style: .plain)
        self.tableView?.delegate = self;
        self.tableView?.dataSource = self;
        self.tableView?.register(RHKeyValueTableViewCell.self, forCellReuseIdentifier: "RHKeyValueTableViewCell")
        self.tableView?.register(RHTextFieldTableCell.self, forCellReuseIdentifier: "RHTextFieldTableCell")
        self.tableView?.register(RHHeadPortraitTableViewCell.self, forCellReuseIdentifier: "RHHeadPortraitTableViewCell")
        self.tableView?.tableFooterView = addFooterView();
        self.view.addSubview(self.tableView!)
        
        self.tableView?.snp.makeConstraints { [weak self](make) in
            guard let weakSelf = self else { return }
            make.top.equalTo(10)
            make.left.equalTo(weakSelf.view.snp.left)
            make.right.equalTo(weakSelf.view.snp.right)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(weakSelf.view.snp.bottom)
            } else {
                make.bottom.equalTo(weakSelf.view.snp.bottom)
            }
        }
    }
    
    @objc func cancel() {
        self.dismiss(animated: true, completion: nil)
    }
    
    func addFooterView() -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: (self.tableView?.frame.width)!, height: 75.0))
        submit = UIButton.xz_commonButtonWithTitle(title:NSLocalizedString("SubmitText", comment: ""), isEnabled: false)
        footerView.addSubview(submit)
        submit.addTarget(self, action: #selector(submitButtonClick), for: .touchUpInside)
        submit.snp.makeConstraints({(make) in
            make.top.equalTo(15.0)
            make.left.equalTo(20.0)
            make.right.equalTo(-20.0)
            make.height.equalTo(44)
        })
        return footerView
    }
    
    @objc func submitButtonClick() {
        let vc = RHHousesListController()
        vc.action = pickerViewDataStorage[0] as? String
        vc.keyword = pickerViewDataStorage[1] as? String
        vc.type = pickerViewDataStorage[2] as? String
        vc.beds = pickerViewDataStorage[3] as? String
        vc.baths = pickerViewDataStorage[4] as? String
        vc.year = pickerViewDataStorage[5] as? String
        vc.minSize = getText(string: (pickerViewDataStorage[6] as? String)!, isMin: true)
        vc.maxSize = getText(string: (pickerViewDataStorage[6] as? String)!, isMin: false)
        vc.minPrice = getText(string: (pickerViewDataStorage[7] as? String)!, isMin: true)
        vc.maxPrice = getText(string: (pickerViewDataStorage[7] as? String)!, isMin: false)
        self.present(RHCustomNavigationController(rootViewController: vc), animated: true) {
        }  
    }
    
    func getText(string :String, isMin: Bool) -> String{
        let splitedArray = string.components(separatedBy: "-")
        return isMin == true ? splitedArray[0] :splitedArray[1]
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 1{
            let cell: RHTextFieldTableCell = tableView.dequeueReusableCell(withIdentifier: "RHTextFieldTableCell", for: indexPath) as! RHTextFieldTableCell
            cell.leftLabel?.text = self.array[indexPath.row]
            cell.rightTextField?.delegate = self
            cell.rightTextField?.tag = indexPath.row
            if pickerViewDataStorage[indexPath.row] as! String != "" {
                cell.rightTextField?.text = pickerViewDataStorage[indexPath.row] as? String
            }else{
                cell.rightTextField?.placeholder = "-"
            }
            return cell
        }else{
            let cell: RHKeyValueTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHKeyValueTableViewCell", for: indexPath) as! RHKeyValueTableViewCell
            cell.leftLabel?.text = self.array[indexPath.row]
            cell.rightLabel?.text = pickerViewDataStorage[indexPath.row] as! String != "" ?  pickerViewDataStorage[indexPath.row] as? String : "-"
            return cell
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.view.endEditing(true)
        if indexPath.row == 0{
            reloadPickerViewData(data: queryMethodsArray as NSArray, index: indexPath.row)
        }else if indexPath.row == 2{
            if HousingTypesArray.count == 0{
                for (index) in self.HouseTypeModel.data ?? [RHHouseTypeResponseDataModel()] {
                    HousingTypesArray.append(index.name!)
                }
            }
            reloadPickerViewData(data: HousingTypesArray as NSArray, index: indexPath.row)
        }else if indexPath.row == 3{
            reloadPickerViewData(data: bedroomNumberArray as NSArray, index: indexPath.row)
        }else if indexPath.row == 4{
           reloadPickerViewData(data: bathNumberArray as NSArray, index: indexPath.row)
        }else if indexPath.row == 5{
            self.datePicker.showView()
        }else if indexPath.row == 6{
            reloadPickerViewData(data: minSizeArray as NSArray, index: indexPath.row)
        }else if indexPath.row == 7{
            reloadPickerViewData(data: maxPriceText as NSArray, index: indexPath.row)
        }
    }
    
    func reloadPickerViewData(data: NSArray, index: Int) {
        pickerViewIndex = index
        pickerViewDataArray = data as! [String]
        pickerView.pickerView.reloadAllComponents()
        pickerView.pickerView.selectRow(0, inComponent: 0, animated: true)
        pickerView.showView()
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerViewDataArray.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
        return String(pickerViewDataArray[row])
    }
    
    @objc func ConfirmClick() {
        pickerViewDataStorage[pickerViewIndex] = pickerViewDataArray[pickerView.pickerView.selectedRow(inComponent: 0)]
        dataValueChanged()
        pickerView.hideView()
        self.tableView?.reloadData()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        view.endEditing(true)
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        pickerViewDataStorage[textField.tag] = textField.text ?? String()
        dataValueChanged()
    }
    
    func dataValueChanged() {
        var isEnabledButton = true
        
        for item in self.pickerViewDataStorage{
            if item as! String == ""{
                isEnabledButton = false
            }
        }
        submit.isEnabled = isEnabledButton
    }
}
